package pers.chao.tool.infrastructure;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * Description: 转换为byte数组
 *
 * @author W.Chao
 * @date 2020/11/14 18:02
 **/
public final class BytesUtil {
	private static final Logger logger = LoggerFactory.getLogger(BytesUtil.class);

	private BytesUtil() {
	}

	/**
	 * 文件转byte数组
	 *
	 * @param file
	 * @return
	 */
	public static byte[] file2ByteArray(File file) {
		byte[] data = null;
		try {
			FileInputStream fileInputStream = new FileInputStream(file);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[4096];
			int n = 0;
			while (-1 != (n = fileInputStream.read(buffer))) {
				byteArrayOutputStream.write(buffer, 0, n);
			}
			data = byteArrayOutputStream.toByteArray();
			fileInputStream.close();
			byteArrayOutputStream.close();
		} catch (IOException e) {
			logger.debug("Converted from File to byte array occur error, exception: {}", e.getMessage());
		}
		return data;
	}

	/**
	 * 输入流转byte数组
	 *
	 * @param stream
	 * @return
	 */
	public static byte[] stream2ByteArray(InputStream stream) {
		byte[] data = null;
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[2048];
		int n = 0;
		try {
			while (-1 != (n = stream.read(buffer))) {
				byteArrayOutputStream.write(buffer, 0, n);
			}
			data = byteArrayOutputStream.toByteArray();
			byteArrayOutputStream.close();
		} catch (IOException e) {
			logger.debug("Converted from InputStream to byte array occur error, exception: {}", e.getMessage());
		}
		return data;
	}
}
